<?php
namespace app\api\controller;

use app\api\model\UserModel;
use app\api\validate\Vildate;
use app\BaseController;
use think\Validate;

class User extends  BaseController
{
    //注册
    public  function  register()
    {
        $data =input('post.');
        $validate = new Validate();
        $result = $validate->scene('register');
        if(!$result){
            echo $validate->getError();
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if($user){
            echo '该手机号已被注册';
        }
        sendAliSms($data['mobile']);
        $mobile = $data['mobile'];
        $code = $data['code'];
        if(checkSmsCode($mobile,$code)){
            return error('发送失败');
        }
        $randStr = createRandStr();
        $password = md5($data['password'].$randStr);
        $data['salt'] = $randStr;
        $data['password'] = $password;
        $data['create_time'] = time();
        if(UserModel::create($data)){
            return success('注册成功');
        }else{
            return error('注册失败');
        }
    }
    public function login(){
        $data = input('post.');
        $validate = new Validate();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return error($validate->getError());
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if(!$user){
            return error('该账号不存在');
        }
        if(md5($data['password'].$user['salt']) != $user['password']){
            return error('密码错误');
        }
        return success('登录成功');
    }
}